// ==UserScript==
// @name         获取天猫图片
// @namespace    http://tampermonkey.net/
// @version      2024-10-20
// @description  try to take over the world!
// @author       You
// @match        https://detail.tmall.com/item.htm?*
// @icon         http://wuweijun.fun/favicon.ico
// @grant        none
// ==/UserScript==

(function() {
  'use strict';



  function loadImg(){
      document.querySelectorAll('.thumbnail--TxeB1sWz .thumbnailPic--QasTmWDm').forEach((item,index)=>{
          var s = item.src;
          // https://img.alicdn.com/imgextra/i4/3503485169/O1CN01fWTP1M1o3RsuAildj_!!0-item_pic.jpg_q50.jpg_.webp
          // https://img.alicdn.com/imgextra/i4/3503485169/O1CN01fWTP1M1o3RsuAildj_!!0-item_pic.jpg_.webp
          var a = s.split('jpg')[0]
          var n = document.querySelector('.mainTitle--O1XCl8e2').innerText.substr(0,30);
          console.log(`${a}_!!0-item_pic.jpg`)
          downloadIamge( n + '-' + index, `${a}jpg`)
      })
  }
  function downloadIamge( name,imgsrc) {//下载图片地址和图片名
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
          let canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          let context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);
          let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
          let a = document.createElement("a"); // 生成一个a元素
          let event = new MouseEvent("click"); // 创建一个单击事件
          a.download = name || "photo"; // 设置图片名称
          a.href = url; // 将生成的URL设置为a.href属性
          a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
  }

  function download(name, url) {
      fetch(url).then((res) => {
          res.blob().then((blob) => {
              const blobUrl = window.URL.createObjectURL(blob);
              // 这里的文件名根据实际情况从响应头或者url里获取
              // const filename = 'user.jpg';
              const a = document.createElement('a');
              a.href = blobUrl;
              a.download = name;;
              a.click();
              window.URL.revokeObjectURL(blobUrl);
          });
      });
  }

  var oLi = document.createElement("div");
  oLi.innerHTML =`
<div style="
  position: absolute;
  top: 146px;
  left: 146px;
  background-color: #7ec1da;
  z-index: 9999;
  width: 45px;
  height: 45px;
  !i;!;
  border-radius: 50%;
  text-align: center;
  line-height: 45px;
  color: #fbefef;
  cursor: pointer;"  id="loadImgTo">图片</div>`

  var body2 = document.body;

  body2.appendChild(oLi)

  document.getElementById('loadImgTo').onclick = loadImg


  // Your code here...
})();